/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     ListNode *next;
 *     ListNode() : val(0), next(nullptr) {}
 *     ListNode(int x) : val(x), next(nullptr) {}
 *     ListNode(int x, ListNode *next) : val(x), next(next) {}
 * };
 */
class Solution {
public:
    ListNode* partition(ListNode* head, int x) {
        ListNode* head1 = new ListNode(-1);
        ListNode* prev1 = head1;
        ListNode* head2 = new ListNode(-1);
        ListNode* prev2 = head2;
        ListNode* cur = head;
        while (cur)
        {
            if (cur->val < x)
            {
                prev1 = prev1->next = cur;
            }
            else
            {
                prev2 = prev2->next = cur;
            }
            cur = cur->next;
        }
        prev1->next = nullptr;
        prev2->next = nullptr;
        prev1->next = head2->next;
        cur = head1->next;
        delete head1;
        delete head2;
        return cur;
    }
};

/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode() : val(0), left(nullptr), right(nullptr) {}
 *     TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
 *     TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
 * };
 */
class Solution {
public:
    TreeNode* sortedArrayToBST(vector<int>& nums) {
        return _sortedArrayToBST(nums, 0, nums.size() - 1);
    }
    TreeNode* _sortedArrayToBST(vector<int>& nums, int left, int right)
    {
        if (left > right) return nullptr;

        int mid = (left + right) / 2;
        TreeNode* root = new TreeNode(nums[mid]);
        root->left = _sortedArrayToBST(nums, left, mid - 1);
        root->right = _sortedArrayToBST(nums, mid + 1, right);
        return root;
    }
};